import Vue from 'vue'
import VueRouter from 'vue-router'

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢
const _import = require('./import-' + process.env.NODE_ENV)

// 加载module下所有router文件
const modules = require.context('./module', false, /\.js$/)
let routeArr = []
modules.keys().forEach(path =>{
  routeArr.push(...modules(path).default)
})
// 遍历导入
function batchImport(arr) {
  arr.forEach(el => {
    if(el.component) {
      el.component = _import(el.component)
    } else { // 没有component默认给个router-view
      el.component = {render: (e) => e("router-view")}
    }
    if(el.children) batchImport(el.children)
  })
}
batchImport(routeArr)


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: _import('layout'),
    children: [
      {
        path: '/',
        redirect: '/index'
      },
      {
        path: '/index',
        name: 'index',
        component: _import('index'),
        meta: {
          keepAlive: true
        }
      },      
      ...routeArr,
      {
        path: '*',
        component: _import('404')
      }
    ]
  }
]

// console.log(routes)

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes,
  scrollBehavior: () => ({ y: 0 })
})

import routeGuard from './routeGuard'
routeGuard(router)

// 解决 ns.$router.replace 跳转不到登录页的问题
const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

export default router
